//引入axios
import type { HttpConfig } from '@/api/type';
import router from '@/router';
import { getStorage, toast, formatUrlParam, delStorage } from '@/assets/js/utils';
import { times, divide } from '@/assets/js/utils/digit';
import { config as langConfig } from "@/assets/js/config";
// import { getWeChatCode } from '@/assets/js/wechat';

class http {
    get = (config: HttpConfig) => {
        let paramsStr = '';
        if (config.data) {
            for (let key in config.data) {
                if (paramsStr == '') {
                    paramsStr = `?${key}=${config.data[key]}`;
                } else {
                    paramsStr += `&${key}=${config.data[key]}`;
                }
            }
        }
        config.url = config.url + paramsStr;
        return request({ ...config, method: 'GET' });
    };

    post = (config: HttpConfig) => {
        return request({ ...config, method: 'POST' });
    };

    put = (config: HttpConfig) => {
        return request({ ...config, method: 'PUT' });
    };

    delete = (config: HttpConfig) => {
        return request({ ...config, method: 'DELETE' });
    };
}
//网络请求封装
const request = (config: HttpConfig) => {
    return awaitWrap(
        new Promise((resolve, reject) => {
            // #ifdef MP-WEIXIN
            //获取当前页面实例
            const currentPage: any = getCurrentPages()[getCurrentPages().length - 1];
            //获取当前页面路径
            const currentPagePath = currentPage.route;
            //获取当前页面参数
            const currentPageOptions = currentPage.options;
            //当前页面的路径+参数
            let currentHref = '/' + currentPagePath + formatUrlParam(currentPageOptions);
            // #endif
            if (!config.header) {
                config.header = { 'Content-Type': 'application/json' };
            }
            if (getStorage('token')) {
                config.header['Authorization'] = getStorage('token');
            }
            config.header['currentLang'] = langConfig.targetLang;
            config.header['platform'] = langConfig.platform;
            //是否对非0业务码情况进行toast提示
            let showErrToast = true;
            if (config.errToast != undefined) showErrToast = false;
            //是否捕获错误业务码进行相应错误码操作
            let catchError = true;
            if (config.catchError != undefined) catchError = false;
            uni.request({
                url: import.meta.env.VITE_APP_BASEURL + config.url,
                method: config.method,
                header: config.header,
                data: config.data,
                success: (res: any) => {
                    //接口请求成功
                    const data = res.data;
                    if (data.code != 0) {
                        //不捕获错误业务码
                        if (!catchError) {
                            reject(data);
                            return;
                        }
                        //判断业务接口返回各状态值
                        switch (data.code) {
                            // token过期重新获取
                            case 10005:
                            case 10004:
								// #ifdef MP-WEIXIN
								delStorage('token');
								uni.redirectTo({
								    url: currentHref
								});
                                return;
								// #endif
                                // #ifndef MP-WEIXIN
								delStorage('token');
                                uni.showModal({
                                    title: '提示',
                                    content: '当前未登录，是否跳转至登录？',
                                    success: async function (res) {
                                        if (res.confirm) {
                                            uni.redirectTo({
                                                url: '/pages/login/account-login'
                                            });
                                        }
                                    }
                                });
                                reject(data);
                                return;
								// #endif
                                break;
                        }
                        //显示错误提示
                        if (showErrToast) {
                            uni.showToast({
                                title: data.message ? data.message : '系统繁忙，请稍后再试',
                                icon: 'none',
                                duration: 2500
                            });
                        }
                        reject(data);
                    } else {
                        resolve(data.data);
                    }
                },
                fail: err => {
                    reject(err);
                    if (showErrToast) {
                        uni.showToast({
                            title: '系统繁忙，请稍后再试',
                            icon: 'none',
                            duration: 2500
                        });
                    }
                }
            });
        })
    );
};

const awaitWrap = (promise: any) => {
    return promise
        .then((data: any) => {
            return [data, null];
        })
        .catch((err: any) => {
            return [null, err];
        });
};

export default new http();
